package com.community.process._1010.common.utils.mp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;


/**
 * Created by Zbs
 * 2023-02-06 15:12
 */
public class TreeNodeHelper {

    public static <T extends BaseTreeNode> String getNewCode(BaseMapper<T> baseMapper, BaseTreeNode parent) {
        if (parent == null){
            // 查找第一级最大code
            String maxCode = findMaxCodeByLevel(baseMapper, 1);
            int c = ObjectUtils.isEmpty(maxCode) ? 0 : Integer.parseInt(maxCode);
            // 越界检查
            Assert.isTrue(c < 99, "Tree code out of bound!");
            return String.format("%02d", c + 1);
        }
        // 父级不为空，查找最大code子节点
        String maxCode = findMaxCodeByParentId(baseMapper, parent.getId());
        int c;
        if (ObjectUtils.isEmpty(maxCode)) {
            c = 0;
        } else {
            String lastTwoDigits = maxCode.length() > 2 ? maxCode.substring(maxCode.length() - 2) : maxCode;
            c = Integer.parseInt(lastTwoDigits);
        }
        // 越界检查
        Assert.isTrue(c < 99, "Tree code out of bound!");
        return parent.getTreeCode() + String.format("%02d", c + 1);
    }

    private static <T extends BaseTreeNode> String  findMaxCodeByLevel(BaseMapper<T> baseMapper, int level) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("IFNULL(MAX(tree_code),'0') as tree_code");
        queryWrapper.eq("level",level);
        queryWrapper.last("LIMIT 1");
        T node = baseMapper.selectOne(queryWrapper);
        String treeCode = node.getTreeCode();
        return StringUtils.hasLength(treeCode) ? treeCode : "0";
    }

    private static <T extends BaseTreeNode> String findMaxCodeByParentId(BaseMapper<T>  baseMapper, Long parentId) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("IFNULL(MAX(tree_code),'0') as tree_code");
        queryWrapper.eq("parent_id",parentId);
        queryWrapper.last("LIMIT 1");
        T node = baseMapper.selectOne(queryWrapper);
        String treeCode = node.getTreeCode();
        return StringUtils.hasLength(treeCode) ? treeCode : "0";
    }
}
